package search

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
	"wechat/global"
	"wechat/handle/model"
	"wechat/handle/request"
)

//好友添加

func AddFriend(c *gin.Context) {
	var form request.AddFriend
	if err := c.ShouldBind(&form); err != nil {
		c.JSONP(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}

	var friend model.Friend
	if err := friend.VeryFriend(global.DB, form.UserId, form.FriendId); err == nil {
		c.JSONP(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "已是好友,请勿重复添加",
		})
		return
	}

	friend = model.Friend{
		UserId:   form.UserId,
		FriendId: form.FriendId,
		Content:  form.Content,
		Status:   form.Status,
	}

	if err := friend.AddFriend(global.DB); err != nil {
		c.JSONP(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "好友添加失败",
		})
		return
	}

	c.JSONP(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "好友添加成功",
	})

}

// 好友列表
func ListFriend(c *gin.Context) {
	var form request.ListFriend
	if err := c.ShouldBind(&form); err != nil {
		c.JSONP(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}

	var friend model.Friend

	listFriend, err := friend.ListFriend(global.DB, form.UserId)
	if err != nil {
		c.JSONP(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "查询失败",
		})
		return
	}

	marshal, err := json.Marshal(listFriend)
	if err != nil {
		return
	}
	global.Rdb.Set(global.Ctx, "listFriend", marshal, time.Minute)

	c.JSONP(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "好友列表查询成功",
		"Data": map[string]interface{}{
			"list": listFriend,
		},
	})

}
